<!doctype html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="md5.js"></script>

</head>
<body>

<button onclick="tt()">测试</button>
<script>
    function tt(){
        var res=ajax('get', {});
        console.log(res);
    }
    function ajax(type='get',data={}) {
        type=type.toUpperCase();
        let url = 'http://你的域名/';
        let path = 'test4.php';   //你的请求地址

        let bodyurl = '/'+path;
        var userstr = encrypt('add', '123123', bodyurl, type,'abc');   //  yourname 和yourpassword，yourrealm是需要和后端统一才行。后端用一个表专门存这些数据

        return new Promise((resolve) =>{
            $.ajax({
                method: type,
                url: `${url}${path}`,
                data:data,
                dataType :'json',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("Authorization",userstr);  //把加密后的字符串添加到头部信息中
                },
                success:(res) =>{
                    resolve(res)
                }
            });
        })
    }
    //加密形成摘要的规则也需要和前端统一
    function encrypt( userName, password,requestUri,method,yourrealm) {
        var usermd = hex_md5(userName + ":"+yourrealm+":" + password);//A1
        var rqmd = hex_md5(method+":"+requestUri);//A2
        console.log(method);
        console.log(rqmd);
        let nonce=1,nc=1,cnonce=1,qop='auth';
        // var mainmd = hex_md5(usermd+":1:1:1:auth:"+rqmd);
        var mainmd = hex_md5(usermd+":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+rqmd);
        var head ='Digest username="'+userName+'", realm="'+yourrealm+'", nonce="1", uri="'+requestUri+'", qop=, nc=1, cnonce="1", response="'+mainmd+'", opaque="1"'
        var head = `Digest username="${userName}", realm="${yourrealm}", nonce="${nonce}", uri="${requestUri}", qop="${qop}", nc=${nc}, cnonce=${cnonce}, response="${mainmd}", opaque="1"`;
        return head;
    }
</script>
</body>
</html>